<?php
class UploadController extends Controller {

	/**
	 * 上传照片到指定aid的相册中
	 *
	 * @param int $id        	
	 */
	public function actionIndex ($id) {
		$aid = (int) $id;
		
		$model = 'Album';
		if (!($album = CActiveRecord::model($model)->findByPk($aid))) $this->showError('抱歉.没有找到相册! 你可以先创建相册.');
		
		if (!$this->module->checkIdentity($aid, 'author')) {
			Yii::app()->user->setFlash('message', '无权上传图片.请先确认身份哟?');
			return Yii::app()->runController('album/check');
		}
		
		$photoModel = 'AlbumPhoto';
		$photo = new $photoModel();
		
		if (isset($_POST[$photoModel]) && is_array($_POST[$photoModel])) { // 保存图片
			$errors = array();
			foreach($_POST[$photoModel] as $key => $data) {
				$clonePhoto = clone $photo;
				$clonePhoto->setAttributes($data);
				$clonePhoto->aid = $aid;
				if (!$clonePhoto->save()) $errors[] = $clonePhoto->getErrors();
			}
			$language = ($num = count($errors)) ? $num . '个图片上传失败' : '上传成功';
			$this->showSuccess($language . ' 现在跳转到相册页面', array(
				'/album/view',
				'id' => $aid 
			));
		}
		
		$fileDataName = 'Filedata';
		if (isset($_FILES[$fileDataName])) { // 上传
			if (!($uploader = UploadedFile::getInstanceByName($fileDataName))) $this->showError('抱歉,没有找到上传照片!');
			if (!$uploader->checkImage()) $this->showError('抱歉,你上传的不是图片!' . $uploader->type);
			if (!($path = $uploader->save('album'))) $this->showError('抱歉,无法保存上传图片!');
			
			$attachment = Yii::app()->getAttachment();
			$thumbArray = $photo->getThumb($path, null, false, true); // 预先生成缩略图
			
			$return = array(
				'path' => $path,
				'url' => $attachment->getUrl($path),
				'thumbUrl' => $attachment->getUrl($thumbArray['thumb']) 
			);
			$this->showSuccess($return);
		}
		$this->render('index', array(
			'aid' => $aid,
			'album' => $album,
			'photo' => $photo 
		));
	}
}
?>